package com.yycx.module.bus.provider.service.impl;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.module.bus.client.entity.BusDrugs;
import com.yycx.module.bus.client.entity.BusDrugslot;
import com.yycx.module.bus.provider.mapper.BusDrugslotMapper;
import com.yycx.module.bus.provider.service.BusDrugslotService;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.module.bus.provider.service.BusOrderDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 批号接口实现类
 *
 * @author flyme
 * @date 2020-08-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusDrugslotServiceImpl extends BaseServiceImpl<BusDrugslotMapper, BusDrugslot> implements BusDrugslotService {

    @Autowired
    private BusOrderDetailsService orderDetailsService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusDrugslot drugslot, EntityMap extra) {
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusDrugslot> cq, BusDrugslot drugslot, EntityMap requestMap) {
        Long drugsId = drugslot.getDrugsId();
        cq.select(BusDrugslot.class, "*");
        cq.addSelect(BusDrugs.class, "drugsName", "drugsSpec");
        cq.eq(BusDrugs.class, "drugsId", drugsId);
        cq.eq(BusDrugslot.class, "drugsLotNo");
        cq.orderByDesc("drugslot.createTime");
        cq.createJoin(BusDrugs.class);
        return ResultBody.ok();
    }

    @Override
    public List<EntityMap> afterPageList(CriteriaQuery<BusDrugslot> cq, List<EntityMap> data, ResultBody resultBody) {
        List<EntityMap> result = new ArrayList<>();
        if (FlymeUtils.isNotEmpty(data)) {
            for (EntityMap datum : data) {
                Long drugsLotId = datum.getLong("drugsLotId");
                BigDecimal saleNum = FlymeUtils.getBigDecimal(orderDetailsService.countByDrugLotId(drugsLotId), "0");
                Integer drugsNum = datum.getInt("drugsNum");
                datum.put("saleNum", saleNum);
                datum.put("surplusNum", new BigDecimal(drugsNum).subtract(saleNum));
                if (FlymeUtils.gtzero(new BigDecimal(drugsNum).subtract(saleNum))) {
                    result.add(datum);
                }
            }
            data = result;
        }
        return super.afterPageList(cq, data, resultBody);
    }
}
